package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.ShoppingCart;
import com.itheima.reggie.service.ShoppingCartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.List;

@RestController
@RequestMapping("/shoppingCart")
public class ShoppingCartController {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private HttpSession session;

    //添加购物车信息
    @RequestMapping("/add")
    public R<ShoppingCart> addCart(@RequestBody ShoppingCart shoppingCart) {
        //获取会话
        Long id = (Long) session.getAttribute("user");
        shoppingCart.setUserId(id);
        //调佣业务层返回结果
        return R.success(shoppingCartService.addCart(shoppingCart));
    }

    //查询购物车信息
    @RequestMapping("/list")
    public R<List<ShoppingCart>> findAllByUserId() {
        //获取会话中的id
        Long id = (Long) session.getAttribute("user");
        return R.success(shoppingCartService.findAllByUserId(id));
    }

    //清空购物车
    @RequestMapping("/clean")
    public R<String> clean() {
        shoppingCartService.deleteByUserId((Long) session.getAttribute("user"));
        return R.success("清空购物车成功");
    }
}
